package com.mind.ridge.service.backend.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mind.ridge.dto.backend.DishDto;
import com.mind.ridge.mapper.backend.DishMapper;
import com.mind.ridge.pojo.backend.Category;
import com.mind.ridge.pojo.backend.Dish;
import com.mind.ridge.pojo.backend.DishFlavor;
import com.mind.ridge.service.backend.CategoryService;
import com.mind.ridge.service.backend.DishFlavorService;
import com.mind.ridge.service.backend.DishService;
import com.mind.ridge.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mind
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishFlavorService dishFlavorService;


    @Resource
    private CategoryService categoryService;

    /**
     * 新增菜品，同时保存对应的口味数据
     *
     * @param dishDto
     */
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);
        Long dishId = dishDto.getId();


        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public R<IPage> page(int page, int pageSize, String name) {
        IPage<Dish> iPage = new Page<>(page, pageSize);
        IPage<DishDto> dtoIPage = new Page<>();

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Dish::getUpdateTime);
        wrapper.like(Strings.isNotEmpty(name), Dish::getName, name);
        this.page(iPage, wrapper);

        BeanUtils.copyProperties(iPage, dtoIPage, "records");
        List<Dish> records = iPage.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());
        dtoIPage.setRecords(list);
        return R.success(dtoIPage);
    }

    @Override
    public R<String> alterStatus(int status, List<Long> ids) {
        if (ids == null) {
            return R.error("未知错误！");
        }
        log.info("状态值：{},id值：{}", status, ids);
        for (Long id : ids) {
            LambdaUpdateWrapper<Dish> luw = new LambdaUpdateWrapper<>();
            luw.eq(Dish::getId, id)
                    .set(Dish::getStatus, status);
            this.update(luw);
        }
        return R.success("修改成功！");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R<DishDto> recurInfo(long id) {
        Dish dish = getById(id);
        Long dishId = dish.getId();

        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dishId != null, DishFlavor::getDishId, dishId);
        List<DishFlavor> list = dishFlavorService.list(lqw);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);

        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    @Override
    public R<String> deleteBatch(List<Long> ids) {
        if (ids == null) {
            return R.error("ERROR");
        }
        boolean b = this.removeByIds(ids);
        return b ? R.success("删除成功") : R.error("删除失败！该记录或已被删除！");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R<String> updateWithFlavor(DishDto dishDto) {
        log.info(dishDto.toString());

        //将dishDto中的数据拷贝到dish中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish);


        //根据id 和 拷贝后的dish 在原有的基础上更新
        LambdaUpdateWrapper<Dish> luw = new LambdaUpdateWrapper<>();
        luw.eq(Dish::getId, dish.getId());
        this.update(dish, luw);

        //获取该菜品的口味
        List<DishFlavor> flavors = dishDto.getFlavors();


        //从口味列表中取出每一条数据，若DishId为空则必定是新添加的口味则将当前的DishId赋给当前的flavor并保存到数据库
        //若DishId不为空，则直接将现有的更新之前的即可
        for (DishFlavor flavor : flavors) {
            if (flavor.getDishId() == null) {
                flavor.setDishId(dish.getId());
                dishFlavorService.save(flavor);
                continue;
            }
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId, dish.getId())
                    .eq(DishFlavor::getId, flavor.getId());
            dishFlavorService.update(flavor, wrapper);
        }
        return R.success("修改成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R<List<DishDto>> categoryList(Long id, Integer status) {
        if (id == null) {
            return R.error("ERROR");
        }
        //根据分类id获取Dish
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId, id).orderByDesc(Dish::getUpdateTime);
        lqw.eq(status != null, Dish::getStatus, status);
        List<Dish> dishList = this.list(lqw);

        List<DishDto> list = dishList.stream().map((item) -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item, dto);
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> flavorWrapper = new LambdaQueryWrapper<>();
            flavorWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavors = dishFlavorService.list(flavorWrapper);
            dto.setFlavors(flavors);
            return dto;
        }).collect(Collectors.toList());

        return R.success(list);
    }

}
